package me.spring.cloud.components.starter.rpc.crypto.service;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import java.io.InputStream;
import me.spring.cloud.common.components.rpc.crypto.service.CryptoService;
import me.spring.cloud.common.components.util.json.JsonUtil;

/**
 * @author luffy
 * @description: RSA
 * @date 2019-11-15 17:28
 */
public abstract class AbstractRsaCryptService implements CryptoService {

  public String encryptBase64(String str, KeyType keyType,RSA rsa) {
    return rsa.encryptBase64(URLUtil.encode(str), keyType);
  }

  public byte[] encrypt(byte[] bytes, RSA rsa) {
    return rsa.decrypt(bytes, KeyType.PublicKey);
  }

  public byte[] encrypt(InputStream is, RSA rsa) {
    return rsa.decrypt(is, KeyType.PublicKey);
  }

  public String encryptForKey(String str, KeyType keyType, RSA rsa) {
    return rsa.encryptBcd(str, keyType);
  }

  @Override
  public String encrypt(Object object) {
    return this.encrypt(JsonUtil.toJSON(object));
  }

  public byte[] decrypt(byte[] bytes, RSA rsa) {
    return rsa.decrypt(bytes, KeyType.PrivateKey);
  }

  public byte[] decrypt(InputStream is, RSA rsa) {
    return rsa.decrypt(is, KeyType.PrivateKey);
  }

  public String decryptForKey(String encrypt, KeyType keyType, RSA rsa) {
    return rsa.decryptStr(encrypt, keyType);
  }

  @Override
  public byte[] decryptForByte(String string) {
    return StrUtil.bytes(this.decrypt(string), CharsetUtil.CHARSET_UTF_8);
  }
}
